<?php
/**
 * 创建者 admin.
 * 日期: 2016/10/19
 * 时间: 15:37
 * 描述：系统公共控制器
 */
namespace Team\Controller;
use Common\Controller\BaseController;
use Think\Auth;

class ComController extends BaseController
{
    public $USER;

    public function _initialize()
    {
        C(setting());
        $flag = false;
        $auth = cookie('auth');
        list($identifier, $token) = explode(',', $auth);
        if (ctype_alnum($identifier) && ctype_alnum($token)) {
            $user = M('member')->field('uid,user,identifier,token,salt,dept_id,type,name,head')->where(array('identifier'=>$identifier))->find();

            if($user) {
                if($token == $user['token'] && $user['identifier'] == password($user['uid'].md5($user['user'].$user['salt']))){
                    $flag = true;
                    $this->USER = $user;
                }
            }
        }

        $url = U("/login");
        if (!$flag) {
            header("Location: {$url}");
            exit(0);
        }
        $m = M();
        $prefix = C('DB_PREFIX');
        $UID = $this->USER['uid'];
        $userinfo = $m->query("SELECT * FROM {$prefix}auth_group g left join {$prefix}auth_group_access a on g.id=a.group_id where a.uid=$UID");
        $Auth = new Auth();
        $allow_controller_name = array('Upload');//放行控制器名称
        $allow_action_name = array();//放行函数名称
        if ($userinfo[0]['group_id'] != 1 && !$Auth->check(CONTROLLER_NAME . '/' . ACTION_NAME, $UID) && !in_array(CONTROLLER_NAME, $allow_controller_name) && !in_array(ACTION_NAME, $allow_action_name)) {
            $info = array(
                "info"=>"没有权限访问!",
                "status"=>"n",
            );
            $this -> ajaxReturn($info,'json');
        }

        $user = member(intval($UID));
        $this->assign('user', $user);


        $current_action_name = ACTION_NAME == 'edit' ? "index" : ACTION_NAME;
        $current = $m->query("SELECT s.id,s.title,s.name,s.tips,s.pid,p.pid as ppid,p.title as ptitle FROM {$prefix}auth_rule s left join {$prefix}auth_rule p on p.id=s.pid where s.name='" . CONTROLLER_NAME . '/' . $current_action_name . "'");
        $this->assign('current', $current[0]);


        $menu_access_id = $userinfo[0]['rules'];

        if ($userinfo[0]['group_id'] != 1) {

            $menu_where = "AND id in ($menu_access_id)";

        } else {

            $menu_where = '';
        }
        //顶部导航栏
        $menu = M('auth_rule')->field('id,title,pid,name,icon')->where("islink=1 AND mold=1 $menu_where ")->order('o ASC')->select();
        $menu = $this->getMenu($menu);
        $this->assign('menu', $menu);
        //顶部右侧菜单
        $sildmenu =  M('auth_rule')->field('id,title,pid,name,icon')->where("islink=1 AND mold=2 $menu_where ")->order('o ASC')->select();
        $sildmenu = $this->getMenu($sildmenu);
        $this->assign('sildmenu', $sildmenu);
        //左侧菜单
        $sildnav =  M('auth_rule')->field('id,title,pid,name,icon')->where("islink=1 AND pid !=0 AND mold=3 $menu_where ")->order('o ASC')->select();
        $sildnav = $this->getMenu( $sildnav);
        $this->assign('sildnav',  $sildnav);
//        dump($sildnav);
    }


    protected function getMenu($items, $id = 'id', $pid = 'pid', $son = 'children')
    {
        $tree = array();
        $tmpMap = array();

        foreach ($items as $item) {
            $tmpMap[$item[$id]] = $item;
        }

        foreach ($items as $item) {
            if (isset($tmpMap[$item[$pid]])) {
                $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
            } else {
                $tree[] = &$tmpMap[$item[$id]];
            }
        }
        return $tree;
    }

    //文件下载
    public function downFile($path = '',$name=''){

        if(!$path) header("Location: /");
        download($path,$name);

    }

    //文件下载
    public function delFile(){

        $uid = $this->USER['uid'];
        $fid = isset($_POST['fid'])?intval($_POST['fid']):false;
        if($uid){
            $data = M('document')->field('path')->where('fid='.$fid)->find();
            $path = $data['path'];
            if(M('document')->where('fid='.$fid)->delete()){
                delFile($path);
                addlog('删除文件，ID：'.$fid);
            }


        }

    }


    //公共分享数据
    public function share($stu =''){
        /* 为空则是参数错误
         * 为file则是文件分享
         * 为word则是笔记分享
        */
        switch($stu){
            case 'file';
                $fid = I('post.fid');
                $pin =isset($_POST['pin'])?$_POST['pin']:false;
                $doc =M('document')->field('name,path,uid')->where("fid={$fid}")->find();//文件数据
                if($pin){
                    $data['pin']= $pin;//PIN码
                }
                $data['source'] = 2;//分享动态

                $data['title']='分享了文件:'.$doc['name'];//保存名字
                $data['content']=$doc['path'];//保存路径
                $data['type']=2;//文件类型
                $data['uid']=$doc['uid'];//主人id
                $data['time']=time();//当前时间
                $sid = M("dynamic")->data($data)->add();
                if($sid){
                    $info = array(
                        "path"=>"{$_SERVER['HTTP_HOST']}/look?sid={$sid}",
                        "status"=>"y",
                    );
                    $this -> ajaxReturn($info,'json');
                }
                break;

            case 'word';
                $wid = I('post.wid');
                $pin =isset($_POST['pin'])?$_POST['pin']:false;
                $data =M('words')->field('title,content,uid')->where("wid={$wid}")->find();//文件数据
                if($pin){
                    $data['pin']= $pin;//PIN码
                }
                $data['source'] = 2;//分享动态
                $data['type']=1;//文章类型
                $data['time']=time();//当前时间
                $sid = M("dynamic")->data($data)->add();
                if($sid){
                    $info = array(
                        "path"=>"{$_SERVER['HTTP_HOST']}/look?sid={$sid}",
                        "status"=>"y",
                    );
                    $this -> ajaxReturn($info,'json');
                }
                break;

            default:
                $info = array(
                    "info"=>"未知参数错误",
                    "status"=>"n",
                );
                $this -> ajaxReturn($info,'json');
                break;
        }

    }

    public function coll(){
        $content = isset($_REQUEST['content'])?$_REQUEST['content']:false;
        if($content){
            $data['name'] = isset($_POST['name'])?$_POST['name']:'';
            $data['content'] = $content;
            $data['uid'] = $this->USER['uid'];
            $data['time'] = time();
            $data['status'] = 1;//加标记
//            dump($data);die;
            //添加数据
            if(M('collection')->data($data)->add()){
                addlog("收藏了链接:".$url);
                $info = array(
                    "info"=>"恭喜操作成功！",
                    "status"=>"y",
                );
                $this -> ajaxReturn($info,'json');
            }

        }
            $info = array(
                "info"=>"警告！参数错误！。",
                "status"=>"n",
            );
            $this -> ajaxReturn($info,'json');


    }

}